import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
    const user = ref(null)
    const token = ref(localStorage.getItem('token') || null)

    const register = async (userData) => {
        try {
            const response = await api.register({
                username: userData.username || '23007609',
                pwd: userData.pwd || '123456',
                age: userData.age || 20,
                realName: userData.realName || '吴晶晶',
                email: userData.email || '',
                stuNum: userData.stuNum || '23007609',
                className: userData.className || '23软件技术1班'
            })
            return response
        } catch (error) {
            throw error
        }
    }

    const login = async (credentials) => {
        try {
            const response = await api.login({
                username: credentials.username || '23007609',
                pwd: credentials.pwd || '123456'
            })
            token.value = response.token
            localStorage.setItem('token', token.value)
            user.value = response.user
            return user.value
        } catch (error) {
            throw error
        }
    }

    const logout = () => {
        localStorage.removeItem('token')
        token.value = null
        user.value = null
    }

    return { user, token, register, login, logout }
})